import React, {useEffect, useRef, useState} from 'react';
import {
  Image,
  Text,
  View,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';
import {chunkArray} from '../utils/jsUtils';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';

const FlatListSm = ({
  list,
  bodyStyle,
  itemStyle,
  checkId,
  status = '',
  headerStatus,
  screenHeight,
  screenWidth,
}) => {
  const [numColumns, setNumColumns] = useState(4); // Default to 4 columns for portrait
  const [stickers, setStickers] = useState([]);
  useEffect(() => {
    const isLandscape = screenWidth > screenHeight;
    setNumColumns(isLandscape ? 6 : 4);
    setStickers(chunkArray(list, isLandscape ? 6 : 4));
  }, [list, screenHeight, screenWidth]);
  let wd = Math.round(screenWidth);
  const styles =
    wd === 1024 || wd === 1365
      ? stylesLG
      : wd === 994 || wd === 1325
      ? stylesMD
      : stylesXS;
  const _renderItem = (item, index) => {
    return (
      <View style={styles.justAlign}>
        <View
          style={[
            styles.justAlign,
            itemStyle,
            (screenWidth < screenHeight && index % 4 === 3) ||
            (screenWidth > screenHeight && index % 6 === 5)
              ? {marginRight: 0}
              : null,
          ]}>
          <View style={styles.justAlign}>
            <Image
              style={[
                styles.cardItemImgSm,
                {
                  resizeMode: 'contain',
                  resizeMethod: 'resize',
                },
              ]}
              source={
                item?.id === 'new_create_group'
                  ? require('../../assets/ic_add_group.png')
                  : !item?.thumb_sticker
                  ? require('../../assets/ic_sticker-think.png')
                  : {uri: `file://${item?.thumb_sticker}`}
              }
            />
          </View>
          <Text
            style={styles.textItemFontSm}
            ellipsizeMode={'middle'}
            numberOfLines={1}>
            {item?.name}
          </Text>
        </View>
      </View>
    );
  };
  return (
    <View style={bodyStyle}>
      <View style={styles.flexCenterWrap}>
        <FlatList
          data={stickers}
          renderItem={({item}) => {
            return (
              <View style={styles.flexCenterWrap}>
                {item && item.map((ite, indx) => _renderItem(ite, indx))}
              </View>
            );
          }}
          initialNumToRender={numColumns}
          showsVerticalScrollIndicator={true}
          contentContainerStyle={{
            paddingHorizontal: styles.borderWidth_4.borderWidth,
          }}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    </View>
  );
};

export default FlatListSm;
